package com.neusoft.bizcore.cloud.config;

import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.neusoft.bizcore.web.exception.AccessDeniedException;
import com.neusoft.bizcore.web.utils.JsonUtils;

import feign.FeignException;
import feign.Logger;
import feign.Response;
import feign.Util;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;

@Configuration
public class BizcoreCloudConfiguration implements ErrorDecoder {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Encoder feignEncoder() {
        return new FeignQueryEncoder(new SpringEncoder(this.messageConverters));
    }

    /**
     * 封装feign调用异常
     */
    @Override
    public Exception decode(final String methodKey, final Response response) {
        if (response.status() == 403) {
            try {
                final Map<String, Object> map = JsonUtils.jsonToMap(Util.toString(response.body().asReader()));
                final String errorMsg = (String) map.get("data");

                final AccessDeniedException e = new AccessDeniedException(errorMsg);
                return e;
            } catch (final IOException e) {
                return new AccessDeniedException("");
            }
        }

        return FeignException.errorStatus(methodKey, response);
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

}
